var DBFactory = require('../db/mysql');
var async = require('async');
var CONFIG = require('./../config');
var PostHelper = require('./../util/postHelper');
var common = require('./../util/common');
var fs = require('fs');
var urlencode = require('urlencode');
var ocrDao = module.exports;

ocrDao.getAccessToken = function (data, cb) {
    var param = {
        client_id: CONFIG.CLIENTID,
        client_secret: CONFIG.CLIENTSECRET,
        grant_type: CONFIG.GRANTTYPE
    }

    PostHelper.baseRequest('https://aip.baidubce.com/oauth/2.0/token', param, function (err, result) {
        if (err) {
            return cb({
                status: 201,
                msg: err
            });
        } else {
            return cb(null, {
                status: 200,
                data: result
            });
        }
    });
}

ocrDao.general_basic = function (data, cb) {
    var param = {
        access_token: CONFIG.ACCESSTOKEN,
        url: data.url
    }

    PostHelper.baseRequest('https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic', param, function (err, result) {
        if (err) {
            return cb({
                status: 201,
                msg: err
            });
        } else {
            return cb(null, {
                status: 200,
                data: result
            });
        }
    });
}

ocrDao.general = function (data, cb) {
    var param = {
        access_token: CONFIG.ACCESSTOKEN,
        url: data.url
    }

    PostHelper.baseRequest('https://aip.baidubce.com/rest/2.0/ocr/v1/general', param, function (err, result) {
        if (err) {
            return cb({
                status: 201,
                msg: err
            });
        } else {
            return cb(null, {
                status: 200,
                data: result
            });
        }
    });
}

ocrDao.handwriting = function (data, cb) {
    var image = fs.readFileSync('./../public/images/begin.jpg').toString('base64');

    PostHelper.baseRequestBase('https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=' + CONFIG.ACCESSTOKEN, image, function (err, result) {
        if (err) {
            return cb({
                status: 201,
                msg: err
            });
        } else {
            return cb(null, {
                status: 200,
                data: result
            });
        }
    });
}

ocrDao.idcard = function (data, cb) {
    var image = fs.readFileSync('./../public/images/front.jpg').toString('base64');

    PostHelper.baseRequestBase('https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + CONFIG.ACCESSTOKEN, {image: image, id_card_side: 'front'}, function (err, result) {
        if (err) {
            return cb({
                status: 201,
                msg: err
            });
        } else {
            return cb(null, {
                status: 200,
                data: result
            });
        }
    });
}